﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;

namespace SMARTMobile.WinPhone
{
    /// <summary>
    /// Represent the MVVM model locator.
    /// </summary>
    public class ViewModelLocator
    {
        #region Fields

        private static readonly object SyncRoot = new object();

        private readonly PageNavigationConfiguration _configuration;
        private readonly IDictionary<string, object> _viewModelMappings = new Dictionary<string, object>();
        
        #endregion

        #region

        public ViewModelLocator()
        {
            if (ViewModelBase.IsInDesignTool) return;

            Current = this;
            this._configuration = PhoneConfiguration.Current.NavigationMap;
        }

        #endregion
        
        public static ViewModelLocator Current
        {
            get;
            private set;
        }

        public object this[string name]
        {
            get
            {
                if (!this._viewModelMappings.ContainsKey(name))
                {
                    lock (SyncRoot)
                    {
                        if (!this._viewModelMappings.ContainsKey(name))
                        {
                            PageNavigationConfiguration.ViewModelMapping vmMapping = this._configuration.FindViewModel(name);
                            if (null == vmMapping)
                                return null;

                            object asObjectModel = vmMapping.GetObject();
                            if (null == asObjectModel)
                                return null;

                            IWinPhoneViewModel viewModel = asObjectModel as IWinPhoneViewModel;
                            Debug.Assert(null != viewModel, "ViewModel does not implement IWinPhoneViewModel");

                            viewModel.ViewName = name;

                            this._viewModelMappings.Add(name, asObjectModel);
                        }
                    }
                }

                return this._viewModelMappings[name];
            }
            set
            {
                if (_viewModelMappings.ContainsKey(name))
                    this._viewModelMappings[name] = value;
                else
                    this._viewModelMappings.Add(name, value);
            }
        }
        
        public void Clear(string modelname)
        {
            lock (SyncRoot)
            {
                if (this._viewModelMappings.ContainsKey(modelname))
                    this._viewModelMappings.Remove(modelname);
            }
        }
    }
}
